import { getUserDetailByIdAPI, getUserInfoAPI, loginAPI } from '@/api/user'
// import { getToken, setToken, removeToken } from '@/utils/auth'
// 引入花裤衩封装好的通过 cookie 持久化 token 的方法
// 原理是 引入了用来处理 cookie 相关的插件 js-cookie

// 修改默认配置
const state = {
  // token: localStorage.getItem('hr_token') || '' // 页面刷新获取本地存储的 token
  // token: getToken() || ''
  token: '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // localStorage.setItem('hr_token', token) // 登录后将 token 存至本地
    // setToken(token)
  },
  removeToken(state) {
    state.token = ''
    // localStorage.removeItem('hr_token') // 退出后将token 从本地移除
    // removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }

}
const actions = {
  async login(context, data) {
    const res = await loginAPI(data)
    // if (res.data.success) {
    context.commit('setToken', res)
    // }
    localStorage.setItem('loginTime', Date.now())
  },
  async getUserInfo(context) {
    const res = await getUserInfoAPI()
    const detail = await getUserDetailByIdAPI(res.userId)
    console.log(detail)
    context.commit('setUserInfo', { ...res, ...detail })
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

